<template>
  <div class="app-container">
    <el-row>
      <el-col :xs="24" class="table_big_bg">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch" :label-width="labelWidth">
              <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
                <!-- <el-form-item label="用户归属水司" prop="tenantId">
                  <el-input
                    v-model="queryParams.tenantId"
                    placeholder="请输入用户归属水司"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item> -->
                <el-form-item label="用户名称" prop="UserName">
                  <el-input
                    v-model="queryParams.UserName"
                    placeholder="请输入用户名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="用户编号" prop="UserID">
                  <el-input
                    v-model="queryParams.UserID"
                    placeholder="请输入用户编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <!-- (0：否，1：是) -->
                <!-- <el-form-item label="删除标志" prop="DeleteMark">
                  <el-select v-model="queryParams.DeleteMark" placeholder="请选择删除标志" clearable style="width: 170px">
                    <el-option label="否" value="0"/>
                    <el-option label="是" value="1"/>
                  </el-select>
                </el-form-item> -->
                <el-form-item>
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8 padding_top_bottom">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:usersxb:add']"
            >新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['basedata:usersxb:edit']"
            >修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:usersxb:remove']"
            >批量删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入</el-button>
          </el-col>
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" :uploadVisible="uploadVisible" @queryTable="getList" @export="handleExport" @upload="handleUpload" :hasPermiExport="['basedata:usersxb:export']"></RightDropdown>
        </el-row>

        <el-table v-loading="loading" :data="usersxbList" @selection-change="handleSelectionChange" max-height="600" ref="table">
          <el-table-column type="selection" width="55" align="center" fixed/>
          <!-- <el-table-column label="自增主键" align="center" prop="ID" v-if="columns[0].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户归属水司" align="center" prop="tenantId"  width="120" v-if="columns[1].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="用户编号" align="center" prop="UserID" v-if="columns[0].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户名称" align="center" prop="UserName" v-if="columns[1].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户手机号码" align="center" prop="UserPhone" width="120" v-if="columns[2].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="证件类型" align="center" prop="IdType" v-if="columns[3].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="证件号码" align="center" prop="UserCode" v-if="columns[4].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户地址" align="center" prop="UserAddress" width="120" v-if="columns[5].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="备注" align="center" prop="ReMark" v-if="columns[6].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户状态" align="center" prop="UserMark" v-if="columns[7].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.user_status" :value="scope.row.UserMark"/>
            </template>
          </el-table-column>
          <el-table-column label="立户时间" align="center" prop="createTime" v-if="columns[8].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
<!--              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>-->
              <span>{{scope.row.createTime}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:usersxb:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:usersxb:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改小用户档案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <!-- <el-form-item label="归属水司" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择归属水司" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.belong_department"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="用户编号" prop="UserID">
          <el-input v-model="form.UserID" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="用户名称" prop="UserName">
          <el-input v-model="form.UserName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="UserPhone">
          <el-input v-model="form.UserPhone" placeholder="请输入用户手机号码" />
        </el-form-item>
        <el-form-item label="证件类型" prop="IdType">
          <el-input v-model="form.IdType" placeholder="请输入证件类型" />
        </el-form-item>
        <el-form-item label="证件号码" prop="UserCode">
          <el-input v-model="form.UserCode" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="用户地址" prop="UserAddress">
          <el-input v-model="form.UserAddress" placeholder="请输入用户地址" />
        </el-form-item>
        <el-form-item label="备注" prop="ReMark">
          <el-input v-model="form.ReMark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="用户状态" prop="UserMark">
          <el-select v-model="form.UserMark" placeholder="请选择用户状态"  style="width: 202px;">
            <el-option v-for="dict in dict.type.user_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUsersxb, getUsersxb, delUsersxb, addUsersxb, updateUsersxb } from "@/api/record/usersxb";
import { getAreasList } from '@/api/basedata/areas'
import { getToken } from "@/utils/auth";

export default {
  name: "Usersxb",
  dicts: ['yes_no', 'belong_department', 'user_status'],
  data() {
    return {
      uploadVisible: true,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/usersxb/importData"
      },
      size:'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '110px',
      // 列信息
      columns: [
        // { key: 0, label: `自增主键`, visible: false },
        // { key: 1, label: `用户归属水司`, visible: false },
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户手机号码`, visible: true },
        { key: 3, label: `证件类型`, visible: true },
        { key: 4, label: `证件号码`, visible: true },
        { key: 5, label: `用户地址`, visible: true },
        { key: 6, label: `备注`, visible: true },
        { key: 7, label: `用户状态`, visible: true },
        { key: 8, label: `立户时间`, visible: true },
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      AreaName:'',
      // 区域树选项
      areaOptions: [],
      // 区域名称
      keyWordName: undefined,
      // 树状态
      treeVisibale: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小用户档案表格数据
      usersxbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        tenantId: null,
        UserName: null,
        DeleteMark: null,
        UserMark: null,
        UserID: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // tenantId: [
        //   { required: true, message: "用户归属水司不能为空", trigger: "blur" }
        // ],
        UserID: [
          { required: true, message: "用户编号不能为空", trigger: "blur" }
        ],
        UserName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        UserMark: [
          { required: true, message: "用户状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getAreaTree();
  },
  mounted() {
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
    AreaName(val){
      this.$refs.areatree.filter(val)
    }
  },
  updated() {
    this.$refs.table.doLayout()
  },
  methods: {
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "户表用户导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 初始化表格 解决表格固定操作列的问题
    init(){
      // 调用接口获取到数据后
      let _self = this
      this.$nextTick(() => {
        window.setTimeout(() => {
          _self.$refs.table.doLayout()
        }, 100)
      })
    },
    filterValue(query){
      if (query !== "") {
        this.areaOptions = this.areaOptions((item) => {
          if(item.areaName.toLowerCase().indexOf(query) > -1){
            return item
          }
        })
      } else {
        this.areaOptions = [];
      }
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.AreaCode = data.id;
      this.handleQuery();
    },
    // 单击下拉框中的数据
    handleSelectTree(data){
      this.form.AreaCode = data.id
    },
    /** 查询区域下拉树结构 */
    getAreaTree() {
      getAreasList().then(response => {
        var list = response.data
        var list_ = JSON.parse(JSON.stringify(list))
        list_.forEach((item) => {
          var obj = {
            id: item.areaCode,
            label: item.areaName,
            children: item.children && item.children.length > 0 ? this.copyTree(item.children) : item.children
          }
          this.areaOptions.push(obj)
        })
      });
    },
    copyTree(list) {
      list.forEach((item) => {
        item.id = item.areaCode;
        item.label = item.areaName;
        item.children = item.children;
        if (item.children && item.children.length) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 改变tree的显示与隐藏
    changeTreeShow(){
      this.treeVisibale =!this.treeVisibale
    },
    /** 查询小用户档案列表 */
    getList() {
      this.loading = true;
      listUsersxb(this.queryParams).then(response => {
        this.usersxbList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.init()
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ID: null,
        tenantId: '710170',
        UserID: null,
        UserName: null,
        UserPhone: null,
        IdType: null,
        UserCode: null,
        UserAddress: null,
        ReMark: null,
        DeleteMark: null,
        UserMark: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加户表用户档案";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.ID || this.ids
      getUsersxb(ID).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改户表用户档案";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ID != null) {
            updateUsersxb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUsersxb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.ID || this.ids;
      const UserIDs = row.UserID || this.userids
      this.$modal.confirm('是否确认删除户表用户档案编号为"' + UserIDs + '"的数据项？').then(function() {
        return delUsersxb(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/usersxb/export', {
        ...this.queryParams
      }, `户表用户_${new Date().getTime()}.xlsx`)
    },
    // 下载模板
    handleUpload(){
      this.download('basedata/usersxb/getImportTemplate', {
      }, `户表用户模板_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
  .form_col{
    width: 80%;
    ::v-deep .el-form {
      width: 100%;
    }
    ::v-deep .el-form-item {
      width: 25%;
    }
  }
  .form_query{
    width: 20%;
    text-align: right;
  }
</style>
